# file_python|wechat_add_friends.py|微信批量添加好友脚本

from appium import webdriver
from selenium.webdriver.common.by import By
from appium.options.android import UiAutomator2Options
import time

# 配置 Appium 所需的参数
desired_caps = {
    "platformName": "Android",
    "platformVersion": "12",  # 例如："10"
    "deviceName": "SM-G988N",  # 例如："emulator-5554"
    "appPackage": "com.tencent.mm",
    "appActivity": ".ui.LauncherUI",
    "noReset": True
}

# 创建Options对象
options = UiAutomator2Options().load_capabilities(desired_caps)

# 连接 Appium 服务器
driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options)

# 等待微信打开
time.sleep(10)

# 微信号列表
wechat_ids = ["Robin_jj"]

for wechat_id in wechat_ids:
    try:
        # 点击通讯录
        search_box = driver.find_element(By.ID, "com.tencent.mm:id/f2s")
        search_box.click()
        time.sleep(2)

        # 点击 + 号
        search_box = driver.find_element(By.ID, "com.tencent.mm:id/hy6")
        search_box.click()
        time.sleep(2)

        # 点击添加朋友
        add_friend = driver.find_element(By.XPATH, "//android.widget.TextView[@text='添加朋友']")
        add_friend.click()
        time.sleep(2)

        # 点击搜索框
        search_box = driver.find_element(By.ID, "com.tencent.mm:id/jcd")
        search_box.click()
        time.sleep(2)


        # 再次查找搜索框元素，避免 StaleElementReferenceException
        search_box = driver.find_element(By.ID, "com.tencent.mm:id/cd7")
        # 输入微信号
        search_box.send_keys(wechat_id)
        time.sleep(2)


        # 点击搜索
        search_button = driver.find_element(By.ID, "com.tencent.mm:id/kms")
        search_button.click()

        # 等待搜索完成
        time.sleep(2)

        # 点击添加到通讯录
        add_to_contacts = driver.find_element(By.XPATH, "//android.widget.TextView[@text='添加到通讯录']")
        add_to_contacts.click()
        time.sleep(2)

        # 页面拖动到底部
        # 获取屏幕尺寸
        size = driver.get_window_size()
        start_x = size['width'] * 0.5
        start_y = size['height'] * 0.8
        end_y = size['height'] * 0.2

        # 执行滑动操作
        driver.swipe(start_x, start_y, start_x, end_y, 800)
        time.sleep(2)  # 等待滑动完成

        # 点击发送按钮
        send_button = driver.find_element(By.ID, "com.tencent.mm:id/e9q") 
        send_button.click()
        time.sleep(2)

        # 返回通讯录页面
        # driver.back()
        # driver.back()

    except Exception as e:
        print(f"添加 {wechat_id} 时出错: {e}")

# 关闭驱动
driver.quit()